package com.hanson.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.entity.GoodsTypeBean;
import com.hanson.mapper.GoodsTypeBeanMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsTypeService {
    @Autowired
    private GoodsTypeBeanMapper goodsTypeBeanMapper;

    public void addGoodsType(GoodsTypeBean goodsTypeBean) {
        goodsTypeBean.setCreateTime(new Date());
        goodsTypeBeanMapper.insert(goodsTypeBean);
    }

    public void modifyGoodsType(GoodsTypeBean goodsTypeBean) {
        GoodsTypeBean returnBean = goodsTypeBeanMapper.selectByPrimaryKey(goodsTypeBean.getId());
        if (null != returnBean) {
            goodsTypeBean.setCreateTime(returnBean.getCreateTime());
            goodsTypeBeanMapper.updateByPrimaryKey(goodsTypeBean);
        }
    }

    public void deleteGoodsType(Integer id) {
        goodsTypeBeanMapper.deleteByPrimaryKey(id);
    }

    public void setIsShow(Integer id, Integer isShow) {
        goodsTypeBeanMapper.updateIsShow(id, isShow);
    }

    public GoodsTypeBean detailGoodsType(Integer id) {
        return goodsTypeBeanMapper.selectByPrimaryKey(id);
    }

    public Page<GoodsTypeBean> listGoodsType(Page<GoodsTypeBean> page, GoodsTypeBean goodsTypeBean) {
        List<GoodsTypeBean> list = goodsTypeBeanMapper.listGoodsType(page, goodsTypeBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                if (c.getPid() == 0) {
                    c.setPidName("顶级");
                } else {
                    GoodsTypeBean pType = goodsTypeBeanMapper.selectByPrimaryKey(c.getPid());
                    if (null != pType) {
                        c.setPidName(pType.getCateName());
                    }
                }
            });
        }
        return page.setRecords(list);
    }

    public Map<String, List<GoodsTypeBean>> selectByPids(List<GoodsTypeBean> typeList) {
        Map<String, List<GoodsTypeBean>> dataMap = new LinkedHashMap<>();
        if (CollectionUtils.isNotEmpty(typeList)) {
            typeList.stream().forEach(c -> {
                List<GoodsTypeBean> goodsTypeBeanList = goodsTypeBeanMapper.selectByPid(c.getId());
                dataMap.put(c.getCateName(), goodsTypeBeanList);
            });
        }
        return dataMap;
    }

    public List<GoodsTypeBean> selecRootType(int pid) {
        return goodsTypeBeanMapper.selectByPid(pid);
    }

    public List<GoodsTypeBean> selecPidAndType(int pid, int type) {
        return goodsTypeBeanMapper.selectByPidAndType(pid, type);
    }
}
